const path = require('path')
const mime = require('mime')
const fs = require('fs')

const multer = require('multer')
// const upload = multer({dest: path.join(__dirname, '../public/uploads/')})
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../public/uploads/'))
  },
  filename: function (req, file, cb) {
    let ext = mime.getExtension(file.mimetype)
    let filename = file.fieldname + '-' + Date.now() + '.' + ext
    cb(null, filename)
  }
})

const limits = {
  fileSize: 200000,
  files: 1
}
const upload = multer({
  storage, limits, fileFilter
}).single('companyLogo')

const uploadMiddleware = (req, res, next) => {
  upload(req, res, function(err) {
    if(err instanceof multer.MulterError) {
      res.render('fail', {
        data: JSON.stringify({
          message: '文件超出200K'
        })
      })
    } else if (err) {
      res.render('fail', {
        data: JSON.stringify({
          message: err.message
        })
      })
    } else {
      // 正常
      const { companyLogo_old } = req.body
      if(req && req.file) {
        if (!req.file && companyLogo_old) {
          let filename = req.file.filename
          try {
            fs.unlinkSync(path.join(__dirname), `../public/uploads/${companyLogo_old}`)
            req.companyLogo = filename
          } catch(err) {
            // req.companyLogo = filename
            console.log(err)
            res.render('fail', {
              data: JSON.stringify({
                message: '失败。'
              })
            })
          }
        } else if(!req.file && companyLogo_old) {
          req.companyLogo = companyLogo_old
        } else {
          req.companyLogo = req.file.filename
        }
      } else if(companyLogo_old) {
        req.companyLogo = companyLogo_old
      } else {
        res.render('fail', {
          data: JSON.stringify({
            message: '失败，请上传图片。'
          })
        })
      }
      next()
    }
  })
}

function fileFilter (req, file, cb) {
  const acceptType = [
    'image/png',
    'image/jpg',
    'image/jpeg'
  ]
  const mimetype = file.mimetype
  if(!acceptType.includes(mimetype)) {
    cb(new Error('文件类型必须是.png,.jpg,.jpeg'))
  } else {
    cb(null, true) // 接受这个文件，使用true
  }
}

module.exports = uploadMiddleware
